import asyncio
import json
from typing import Dict, Any
from intelli_port.robot_control.executor import create_robot_executor
from intelli_port.commons.observability import robot_retry_processed_total, robot_retry_queue_pops_total, robot_retry_last_activity_ts


async def start_robot_retry_worker(app) -> None:
    r = getattr(app.state, "redis", None)
    if r is None:
        return
    execu = create_robot_executor()
    while True:
        try:
            item = r.blpop("robot:retry", timeout=1)
            if not item:
                await asyncio.sleep(0.1)
                continue
            _, data = item
            robot_retry_queue_pops_total.inc()
            try:
                payload: Dict[str, Any] = json.loads(data.decode("utf-8"))
            except Exception:
                robot_retry_processed_total.labels(result="bad_payload").inc()
                continue
            rid = int(payload.get("robot_id") or 0)
            tid = int(payload.get("task_id") or 0)
            target = payload.get("target") or {}
            backoff_ms = int(payload.get("backoff_ms") or 0)
            if backoff_ms > 0:
                await asyncio.sleep(backoff_ms / 1000.0)
            try:
                execu.navigate_to(rid, {"type": "navigate", "target": target, "task_id": tid})
                robot_retry_processed_total.labels(result="sent").inc()
            except Exception:
                robot_retry_processed_total.labels(result="error").inc()
            try:
                import time
                robot_retry_last_activity_ts.set(time.time())
            except Exception:
                pass
        except Exception:
            await asyncio.sleep(0.5)